<template>
  <div>
    <v-chart
      v-if="config && showChart"
      ref="chart"
      :style="{
        width: chartWidth + 'px',
        height: chartHeight + 'px',
      }"
      :option="option"
      @click="handleChartClick"
    />
    <ToolboxWindow
      title="ChartOption"
      :width="480"
      :show="showChartOption"
      @close="showChartOption = false"
    >
      <pre>{{ option }}</pre>
    </ToolboxWindow>
  </div>
</template>

<script setup>
// import vue apis
import { ref, computed, nextTick, watch, onMounted, onUnmounted, h } from "vue";
import dayjs from "dayjs";

// import stores
import useFlowStore from "@/store/flow.js";
import useCommonStore from "@/store/common.js";

import ToolboxWindow from "@/components/ToolboxWindow";
import pre from "@/utils/pre.js";

// import echarts
// import { use } from "echarts/core";
import * as echarts from "echarts/core";
import "echarts/lib/component/polar";
import { CanvasRenderer, SVGRenderer } from "echarts/renderers";
import {
  BarChart,
  LineChart,
  ScatterChart,
  EffectScatterChart,
} from "echarts/charts";
import {
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PolarComponent,
} from "echarts/components";
import { LabelLayout, UniversalTransition } from "echarts/features";

// import vue echarts
import VChart, { THEME_KEY } from "vue-echarts";

echarts.use([
  CanvasRenderer,
  // SVGRenderer,
  BarChart,
  LineChart,
  ScatterChart,
  EffectScatterChart,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PolarComponent,
  LabelLayout,
  UniversalTransition,
]);

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
  yMax: {
    type: Number,
    default: null,
  },
});

const showChart = ref(true);
const refresh = async () => {
  showChart.value = false;
  await nextTick();
  showChart.value = true;
};
defineExpose({ refresh });

// const seriesData = computed(() => JSON.parse(JSON.stringify(props.data)));

const flowStore = useFlowStore();
const commonStore = useCommonStore();
const chartObject = ref("chart");
const config = computed(() => flowStore.chartConfig.freeChart);

const staticConfig = {
  barOpacity: 0.9,
  itemStyle: {
    borderRadius: 8,
    borderColor: commonStore.darkMode
      ? "rgba(255,255,255,0.5)"
      : "rgba(0,0,0,0.3)",
    borderWidth: 2,
  },
  emphasisConfig: {
    disabled: false,
    // scale: true,
    // focus:'none',
    // focus: "self",
    focus: config.value.chartEmphasis ? "series" : "none",
  },
  labelConfig: {
    show: true,
    formatter: (item) => (item.value == 0 ? "" : item.value),
    color: commonStore.darkMode ? "#fff" : "#000",
    textBorderColor: commonStore.darkMode ? "#0006" : "#fff8",
    textBorderWidth: 1,
    textShadowColor: commonStore.darkMode ? "#000" : "#fff",
    textShadowBlur: 4,
    textShadowOffsetY: 1,
    fontSize: "14px",
    fontWeight: "bold",
  },
  barMinHeight: 20,
};

const chartWidth = computed(
  () => props.chartData.moments.length * config.value.chartSize + 120
);

const chartHeight = computed(() => commonStore.clientHeight - 179 - 50);

const computedSymbolSize = (value) => {
  if (config.value.chartType == "line") {
    return 4;
  } else {
    // return Math.max(value * 4, 12);
    return value * 4;
  }
};

const option = computed(() => {
  return {
    grid: {
      x: 30,
      y: 40,
      x2: 30,
      y2: 30,
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: { type: "cross" },
    },

    xAxis: {
      type: "category",
      data: props.chartData.moments.map((item) => {
        let diff = dayjs().diff(item, "minute");
        let passed = diff < 0 ? 1 : diff > config.value.dataStep * 15 ? -1 : 0;
        return {
          // value: `${item.format("HHmm")}\n至\n${item
          //   .add(30, "minute")
          //   .format("HHmm")}`,
          value: item.format("HHmm") + " +" + config.value.dataStep * 15,
          textStyle: {
            color:
              passed === 1
                ? commonStore.darkMode
                  ? "#DDD"
                  : "#333"
                : passed === 0
                ? commonStore.darkMode
                  ? "#000"
                  : "#FFF"
                : commonStore.darkMode
                ? "#666"
                : "#AAA",
            fontWeight: passed === 0 ? "bold" : "normal",
            opacity: passed === 0 ? 1 : 0.9,
            overflow: "break",
            // borderWidth: passed === 0 ? 1 : 0,
            // borderColor: commonStore.darkMode ? "#ff6767" : "#775845",
            borderRadius: 6,
            padding: [3, 4, 1, 4],
            backgroundColor:
              passed === 0
                ? commonStore.darkMode
                  ? "#66f"
                  : "#00f"
                : "transparent",
          },
        };
      }),
    },
    yAxis: [
      {
        id: 0,
        type: "value",
        name: "架次",
        position: "left",
        axisLine: { show: true },
        max: props.yMax,
      },
    ],
    series: props.chartData.series.map((target, targetIndex) => {
      if (targetIndex == 0) {
        // 合计
        target.type = "line";
        target.yAxisIndex = 0;
        target.coordinateSystem = "cartesian2d";
        target.smooth = config.value.chartSmooth;
        target.emphasis = staticConfig.emphasisConfig;
        target.label = {
          show: true,
          color: commonStore.darkMode ? "#000" : "#FFF",
          textBorderColor: commonStore.darkMode
            ? "rgba(255,255,255,0.75)"
            : "rgba(0,0,0,0.75)",
          textBorderWidth: 2,
          fontSize: "16px",
          fontWeight: "bold",
          distance: 10,
        };
        (target.lineStyle = {
          color: commonStore.darkMode ? "#fff6" : "#0004",
          opacity: config.value.showTotalLine ? 1 : 0,
          width: 8,
        }),
          (target.itemStyle = {
            color: "#ABB2B9",
          });
        target.clip = false;
        target.animationDelay = function (idx) {
          return idx * 50 + 100;
        };
      } else {
        // 普通系列
        target.barMinHeight = staticConfig.barMinHeight;
        target.type = config.value.chartType;
        target.smooth = config.value.chartSmooth;
        target.coordinateSystem = "cartesian2d";
        target.yAxisIndex = 0;
        target.stack = config.value.chartStack ? "x" : "";
        target.symbolSize = (value) => computedSymbolSize(value);
        target.rippleEffect = { brushType: "stroke" };
        target.label = staticConfig.labelConfig;
        target.emphasis = staticConfig.emphasisConfig;
        target.itemStyle = {
          opacity: staticConfig.barOpacity,
          ...staticConfig.itemStyle,
        };
        // Color
        if (target.definedColor) {
          target.itemStyle.color = target.definedColor;
        }
        target.areaStyle = { opacity: 0.8 };
        target.animationDelay = function (idx) {
          return idx * 50 + 100;
        };
      }
      return target;
    }),
    darkMode: commonStore.darkMode,
    animationEasing: "elasticOut",
    animationDelayUpdate: function (idx) {
      return idx * 5;
    },
  };
});

const emits = defineEmits(["chartClick"]);
const showChartOption = ref(false);
const handleChartClick = (target) => {
  if (target.event.event.ctrlKey) {
    showChartOption.value = true;
  } else {
    emits("chartClick", target.dataIndex);
  }
};
</script>
